package com.qz.mos.filter;

import com.qz.mos.Mos2Application;
import com.qz.mos.service.RestDataService;
import com.qz.mos.entity.RestData;
import com.qz.mos.entity.RestDataMD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关全局异常处理器
 *  :处理网关过滤器、request、response出现问题的情况
 *  不合法参数问题*/
@Configuration
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {
    //日志对象
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionConfiguration.class);
    @Override //参数1: request response   ex:出现异常时异常对象
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.info( "=============离线数据启用===========" );
        log.info( "url：{}" ,exchange.getRequest().getPath());
        log.info( "请求方式：{}" ,exchange.getRequest().getMethodValue());
        RestData restData = null;
        //1.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //2.response是否结束  用于多个异常处理时候
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        List <RestData> data;
        RestDataService bean = Mos2Application.applicationContext.getBean( RestDataService.class );
        MultiValueMap <String, String> queryParams = request.getQueryParams();
        RestData restData1 = Mos2Application.restDataThreadLocal.get();
        if ("POST".equals( request.getMethodValue() )&&restData1!=null) {
            RestDataMD5 body = restData1.getBody();
            String data1 = body.getData();
            data = bean.getData( request.getPath().toString(), request.getMethodValue(),request.getHeaders(),  queryParams, data1 );
            Mos2Application.restDataThreadLocal.remove();
            if(data.isEmpty()){
                return Mono.error(ex);
            }
        }else{
            data = bean.getData( request.getPath().toString(),request.getMethodValue(), request.getHeaders(), queryParams );
        }
        if(data.isEmpty()){
            return Mono.error(ex);
        }
        restData= data.get( 0 ) ;

        if(restData==null){
            return Mono.error(ex);
        }
        String respType = restData.getRespType();
        response.getHeaders().set("Content-Type" , respType.toUpperCase().endsWith( "UTF-8" )?respType:(respType+";charset=UTF-8"));
        RestData finalRestData = restData;
        return response
                .writeWith(Mono.fromSupplier(() -> {
                    DataBufferFactory bufferFactory = response.bufferFactory();
                    return bufferFactory.wrap( finalRestData.getResBody().getPic());
                }));
    }
}
